import React, { useMemo, useEffect, useState } from 'react';
import { Button, Space, Spin, Tag, Typography, message, Switch, Modal } from 'antd';
import type Umi from 'umi';
import { connect, validateFn, useParams, useLocation } from 'umi';
import { isEmpty } from 'lodash';

import style from './index.less';
import Preview from './preview';
import CubeList from './cubeList';
import useDispatcher from './hooks/useDispatcher';
import useInitPageData from './hooks/useInitPageData';

const { Link, Title } = Typography;

type PropsFromModel = Umi.TDecorationModelState;

// interface IEditorProps extends React.PropsWithChildren, PropsFromModel {}

const Editor: React.FC<any> = (props) => {
  console.log(props);

  const {
    preview,
    activeSortItemId,
    pageSetting,
    errorMap,
    loading,
    pageParam,
    showPreViewItems,
    previewCode,
    goodsList,
  } = props;
  console.log('previewCode=>>>>>>', previewCode);
  const { isEdit, isCreate } = useInitPageData();
  const dispatch = useDispatcher();

  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (previewCode) {
      setOpen(true);
    }
  }, [previewCode]);

  const validateData = async () => {
    const pageSettingValid = await validateFn(pageSetting);

    const result = {};
    for (const cube of preview) {
      const valid = await validateFn(cube);
      if (!isEmpty(valid)) {
        result[cube.id] = valid;
      }
    }
    const res = {
      ...(isEmpty(pageSettingValid) ? {} : { page: pageSettingValid }),
      ...result,
    };
    dispatch('setErrorMap', res);
    return isEmpty(res);
  };

  const save = async () => {
    const isOk = await validateData();
    if (isOk) {
      dispatch('save', {});
    } else {
      message.error('部分组件或者页面配置存在数据缺失, 请解决后再提交!');
    }
  };

  const draftSave = () => {
    dispatch('save', {
      isDraft: true,
    });
  };

  const draftPreview = async () => {
    const isOk = await validateData();
    if (isOk) {
      dispatch('preview', {});
    } else {
      message.error('部分组件或者页面配置存在数据缺失, 请解决后再提交!');
    }
  };

  const changeSettingHandle = (type = '') => {
    if (type === 'page') {
      dispatch('setActiveSortItemId', { id: '' });
    } else {
      if (preview.length > 0) {
        dispatch('setActiveSortItemId', { id: preview[0].id });
      }
    }
  };

  const activeSortItem = useMemo(() => {
    if (activeSortItemId && !isEmpty(preview)) {
      return preview.find((p: any) => p.id === activeSortItemId);
    }
    if (!activeSortItemId) {
      return pageSetting;
    }
    return;
  }, [activeSortItemId, preview, pageSetting]);

  const toggleShowPreViewItems = () => {
    dispatch('setShowPreViewItems', !showPreViewItems);
  };
  console.log('activeSortItem=>>>>', activeSortItem);

  const SortItemForm = activeSortItem ? activeSortItem.form : () => null;

  const goodsMap = activeSortItem?.type === 'Goods' ? { goodsList } : {};
  console.log('SortItemForm=>>>>', SortItemForm);

  const Background = pageSetting.view;
  return (
    <Spin spinning={loading}>
      <div className={style.container}>
        <div className={style.header}>
          <Space align="baseline">
            <Title level={3}>{pageParam.name || '页面名称'}</Title>
            {isEdit && (
              <Tag color="processing">
                {['草稿', '已发布', '使用中', '定时发布'][pageParam.status]}
              </Tag>
            )}
          </Space>
          <Space>
            <Button type="text" onClick={draftPreview}>
              预览
            </Button>
            <Button type="text" onClick={draftSave}>
              保存草稿
            </Button>
            <Button type="primary" shape="round" onClick={save}>
              发布
            </Button>
          </Space>
        </div>
        <div className={style.content}>
          <div className={style['content-inner']}>
            <div className={style.left}>
              <div className={style['left-tab']}>
                <Link>组件</Link>
              </div>
              <div className={style['left-content']}>
                <CubeList data={props.groupCubes} previewList={props.preview} />
              </div>
            </div>
            <div className={style.center}>
              <Background data={pageSetting.initialValues}>
                <Preview
                  showPreViewItems={showPreViewItems}
                  activeId={activeSortItemId}
                  itemList={props.preview}
                  errorMap={errorMap}
                  goodsList={goodsList}
                />
              </Background>
            </div>
            <div className={style.right}>
              <div className={style['btn-box']}>
                <div
                  className={`${style['btn-box-item']} ${!activeSortItemId ? style.active : ''}`}
                  onClick={() => changeSettingHandle('page')}
                >
                  页面设置
                </div>
                <div
                  className={`${style['btn-box-item']} ${activeSortItemId ? style.active : ''}`}
                  onClick={() => changeSettingHandle()}
                >
                  组件设置
                </div>
              </div>
              <div className={style['right-inner']}>
                <div className={style['right-inner-header']}>
                  <Title level={4}>{activeSortItem?.title}</Title>
                  {!activeSortItemId && (
                    <Switch
                      checkedChildren="展示"
                      unCheckedChildren="隐藏"
                      checked={showPreViewItems}
                      onChange={toggleShowPreViewItems}
                    />
                  )}
                </div>
                <div className={style['right-inner-body']}>
                  <SortItemForm
                    key={activeSortItem?.id}
                    // @ts-ignore
                    data={activeSortItem?.initialValues || ({} as any)}
                    {...goodsMap}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      {/* 预览 */}
      <Modal
        title="请使用微信扫一扫预览"
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={300}
      >
        <div>
          <img
            style={{
              width: '200px',
              height: '200px',
              display: 'flex',
              marginLeft: 'auto',
              marginRight: 'auto',
            }}
            src={previewCode}
          />
        </div>
      </Modal>
    </Spin>
  );
};

export default connect(({ decoration }: { decoration: PropsFromModel }) => ({
  ...decoration,
}))(Editor);
